package com.mrx.pvzcommunity.service;

import com.mrx.pvzcommunity.dao.PlantDao;
import com.mrx.pvzcommunity.model.Response;
import com.mrx.pvzcommunity.model.Result;
import com.mrx.pvzcommunity.model.pvz.Plant;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PlantService {

    private final PlantDao plantDao;

    private final Base64.Decoder decoder = Base64.getDecoder();

    private static final Logger logger = LoggerFactory.getLogger(PlantService.class);

    public Result<List<Plant>> findPlantByEnv(String env) {
        List<Plant> res = plantDao.findPlantByEnv(env);
        if (res.isEmpty()) {
            return Result.createResult(Response.Code.NOT_FOUND, Collections.emptyList());
        }
        return Result.createResult(Response.Code.SUCCESS, res);
    }

    public Result<List<Plant>> findPlantByName(String name) {
        List<Plant> res = plantDao.findPlantByName(name);
        if (res.isEmpty()) {
            return Result.createResult(Response.Code.NOT_FOUND, Collections.emptyList());
        }
        return Result.createResult(Response.Code.SUCCESS, res);
    }

    public Result<List<Plant>> findPlantByDisposable(Boolean dp) {
        List<Plant> res = plantDao.findPlantByDisposable(dp ? "1" : "0");
        if (res.isEmpty()) {
            return Result.createResult(Response.Code.NOT_FOUND, Collections.emptyList());
        }
        return Result.createResult(Response.Code.SUCCESS, res);
    }

    public Result<List<Plant>> findPlantByEnvAndDp(String env, Boolean dp) {
        List<Plant> res = plantDao.findPlantByEnvAndDp(env, dp ? "1" : "0");
        if (res.isEmpty()) {
            return Result.createResult(Response.Code.NOT_FOUND, Collections.emptyList());
        }
        return Result.createResult(Response.Code.SUCCESS, res);
    }

    public Result<List<Plant>> getAllPlants() {
        List<Plant> res = plantDao.getAllPlants();
        if (res.isEmpty()) {
            return Result.createResult(Response.Code.NOT_FOUND, Collections.emptyList());
        }
        return Result.createResult(Response.Code.SUCCESS, res);
    }

    public byte[] getImgByPlantId(String pid) {
        String img = plantDao.getPlantImgById(pid);
        logger.info("get img: {}", pid);
        try {
            return decoder.decode(img);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
